﻿using System.Collections.Generic;
using System.Linq;

namespace Infrastructure.Base.Utils
{
    public class SearchHelper<TValue> where TValue : class
    {
        private readonly Dictionary<string, List<TValue>> _dictPinyin = new Dictionary<string, List<TValue>>();

        public SearchHelper(IEnumerable<TValue> values)
        {
            initializer(values);
        }

        private void initializer(IEnumerable<TValue> values)
        {
            IList<TValue> enumerable = values as IList<TValue> ?? values.ToList();
            enumerable.ToList().ForEach(item =>
            {
                string key = ChineseUtil.ToFirstLettersPinyin(item.ToString()).ToUpper();
                if (_dictPinyin.ContainsKey(key))
                    _dictPinyin[key].Add(item);
                else
                    _dictPinyin.Add(key, new List<TValue> {item});
            });
        }

        public List<TValue> GetValue(string keyPartial)
        {
            if (ChineseUtil.IsPinyin(keyPartial))
            {
                string key = keyPartial.ToUpper();
                var items = new List<TValue>();
                _dictPinyin.Where(item => item.Key.Contains(key))
                    .Select(item => item.Value)
                    .ToList()
                    .ForEach(items.AddRange);
                return items;
            }
            else
            {
                string key = ChineseUtil.ToFirstLettersPinyin(keyPartial).ToUpper();
                var items = new List<TValue>();
                _dictPinyin.Where(item => item.Key.Contains(key))
                    .Select(item => item.Value)
                    .ToList()
                    .ForEach(items.AddRange);
                return items;
            }
        }
    }
}